-- DungeonBankM
-- Create by chengb Jan/7/2015
-- 地牢银行模块

module("DungeonBankM", package.seeall);

local PURE_FILE = "DungeonBankM"

-- 银行兑换信息
local exchangeTimesInfo = {};
local exchangeTimes;

-- 模块初始化
function init()
    exchangeTimesInfo = {};
    exchangeTimes = nil;
end

-- 重置某地牢层的已兑换次数
function resetExchangeTimes(layer)
    exchangeTimes = 0;
end

-- 获取某地牢层的已兑换次数
function getExchangeTimes(layer)
    return exchangeTimes or 0;
end

-- 增加某地牢层的兑换次数
function addExchangeTimes(layer)
    exchangeTimes = getExchangeTimes(layer) + 1;
end

-- 设置次数
function setExchangeTimes(layer, times)
    exchangeTimes = times;
end

-- 判断能否执行兑换
function canDoExchange(layer)
    if SkyInstanceM.isInSkyInstance() then
        trace(PURE_FILE, "天空特殊副本中无法执行兑换。");
        return false;
    end

    if AwakeM.isInAwake() then
        trace(PURE_FILE, "觉醒地牢中无法执行兑换。");
        return false;
    end

    -- 计算兑换消耗
    local cost = calcExchangeCost(layer);

    -- 只考虑用一种属性（钻石）换
    if ME.user.dbase:query(cost[1], 0) < cost[2] then
        return cost[1] .. "_lack";
    end

    return true;
end

-------------------------
-- 执行兑换
-- @param layer 当前所在的地牢层
-- @return 兑换是否成功
function doExchange(layer)
    if not DungeonM.checkDungeonAction() then
        -- 经检测，不允许执行地牢行为
        trace(PURE_FILE, "经检测，不允许执行地牢行为");
        return false;
    end

    local cost  = calcExchangeCost(layer);
    local bonus = getBonus(layer);

    -- 经判断不能兑换
    if not canDoExchange(layer) then
        return false;
    end

    -- 扣除消耗属性
    ME.user:costAttrib(cost[1], cost[2]);

    -- 获得兑换属性
    BonusM.doBonus(bonus, "bank");

    -- 增加兑换次数
    addExchangeTimes(layer);

    -- 抛出银行兑换成功事件
    EventMgr.fire(event.BANK_EXCHANGE_DONE, {
        ["layer"] = layer,
        ["bonus"] = bonus,
        ["gem"]   = cost[2],
    });
    return true;
end

-- 获取兑换获得的属性信息
function getBonus(layer)
    local dugeonId = DungeonM.getDungeonId();
    if dugeonId == nil then
        dugeonId = user.dbase:query("currentDungeon");
    end
    local layerFix = DungeonAreaM.query(dugeonId, "layer_fix");

    local times = getExchangeTimes(layer);
    return FormulaM.invoke("GET_DUNGEON_BANK_EXCHANGE_ATTRIB", layer, layerFix, times);
end

-- 计算地牢银行兑换消耗
function calcExchangeCost(layer)
    local times = getExchangeTimes(layer);
    return FormulaM.invoke("CALC_DUNGEON_BANK_EXCHANGE_COST", layer, times);
end
